package cn.lijiajia3515.cairo.starter.feign.autoconfigure;

import cn.lijiajia3515.cairo.starter.feign.properties.CairoFeignOAuth2ClientProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;

@Configuration
public class CairoFeignOAuth2ClientAutoConfiguration {

	@Bean
	@ConfigurationProperties(prefix = "cairo.feign.oauth2.client")
	public CairoFeignOAuth2ClientProperties serviceOAuth2Properties() {
		return new CairoFeignOAuth2ClientProperties();
	}

	@Bean
	@ConditionalOnBean(CairoFeignOAuth2ClientProperties.class)
	public OAuth2RestTemplate oAuth2RestTemplate(CairoFeignOAuth2ClientProperties properties) {
		final ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails();
		resource.setClientId(properties.getClientId());
		resource.setClientSecret(properties.getClientSecret());
		resource.setScope(properties.getScopes());
		resource.setGrantType(properties.getGrantType());
		resource.setAccessTokenUri(properties.getAccessTokenUrl());
		resource.setAuthenticationScheme(properties.getAuthenticationScheme());
		OAuth2ClientContext context = new DefaultOAuth2ClientContext();
		return new OAuth2RestTemplate(resource, context);
	}
}
